package com.itv.email.pool;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * User: xia
 * Date: 14-5-26
 * Time: 下午9:22
 */
public class ConnectNetWork {
    /**
     * 执行CMD命令,并返回String字符串
     *
     * @param strCmd
     * @return
     * @throws Exception
     */
    public static String exeCmd(String strCmd) throws Exception {
        Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);
        StringBuilder sbCmd = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sbCmd.append(line + "\n");
        }
        return sbCmd.toString();
    }

    /**
     * 切断ADSL
     *
     * @param adslTitle
     * @return
     * @throws Exception
     */
    public static boolean cutAdsl(String adslTitle) throws Exception {
        // 加上"" 防止空格
        String cutAdsl = "rasdial \"" + adslTitle + "\" /disconnect";
        String result = exeCmd(cutAdsl);
        if (result.indexOf("没有连接") != -1) {
            System.err.println(adslTitle + "连接不存在!");
            return false;
        } else {
            System.out.println("连接已断开");
            return true;
        }
    }

    /**
     * 连接ADSL
     *
     * @param adslTitle
     * @param adslName
     * @param adslPass
     * @return
     * @throws Exception
     */
    public static boolean connAdsl(String adslTitle, String adslName,
                                   String adslPass) throws Exception {
        // 加上"" 防止空格
        String adslCmd = "rasdial \"" + adslTitle + "\" " + adslName + " "+ adslPass;
        String tempCmd = exeCmd(adslCmd);
        if (tempCmd.indexOf("已连接") > 0) {
            System.out.println("已成功建立连接.");
            return true;
        } else {
            System.err.println(tempCmd);
            System.err.println("建立连接失败");
            return false;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // rasdial "宽带名" /disconnect
        String adsl = "宽带连接";
        String username = "020002132648";
        String password = "10567566";
        //cutAdsl(adsl);
        //Thread.sleep(4000);
        connAdsl(adsl, username, password);

    }
}
